package com.tb.emoji;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import android.widget.TextView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class EmojiUtil {
    private static ArrayList<Emoji> emojiList;

    public static ArrayList<Emoji> getEmojiList() {
        if (emojiList == null) {
            emojiList = generateEmojis();
        }
        return emojiList;
    }

    private static ArrayList<Emoji> generateEmojis() {
        ArrayList<Emoji> list = new ArrayList<>();
        for (int i = 0; i < EmojiResArray.length; i++) {
            Emoji emoji = new Emoji();
            emoji.setImageUri(EmojiResArray[i]);
            emoji.setContent(EmojiTextArray[i]);
            list.add(emoji);
        }
        return list;
    }


    public static final int[] EmojiResArray = {
            R.drawable.smile,
            R.drawable.grimance,
            R.drawable.drool,
            R.drawable.scowl,
            R.drawable.cool_guy,
            R.drawable.sob,
            R.drawable.shy,
            R.drawable.silent,
            R.drawable.sleep,
            R.drawable.cry,
            R.drawable.akward,
            R.drawable.angry,
            R.drawable.tongue,
            R.drawable.grin,
            R.drawable.surprise,
            R.drawable.frown,
            R.drawable.ruthless,
            R.drawable.blush,
            R.drawable.scream,
            R.drawable.puke,
            R.drawable.chuckle,
            R.drawable.joyful,
            R.drawable.slight,
            R.drawable.smug,
            R.drawable.hungry,
            R.drawable.drowsy,
            R.drawable.panic,
            R.drawable.sweat,
            R.drawable.laugh,
            R.drawable.drowsy,
            R.drawable.panic,
            R.drawable.scold,
            R.drawable.shocked,
            R.drawable.shhh,
            R.drawable.dizzy,
            R.drawable.tormented,
            R.drawable.toasted,
            R.drawable.skull,
            R.drawable.hammer,
            R.drawable.wave,
            R.drawable.speechless,
            R.drawable.nose_pick,
            R.drawable.clap,
            R.drawable.shame,
            R.drawable.trick,
            R.drawable.bah_l,
            R.drawable.bah_r,
            R.drawable.yawn,
            R.drawable.pooh_pooh,
            R.drawable.shrunken,
            R.drawable.tearing_up,
            R.drawable.sly,
            R.drawable.kiss,
            R.drawable.wrath,
            R.drawable.whimper,
            R.drawable.cleaver,
            R.drawable.watermelon,
            R.drawable.beer,
            R.drawable.basketball,
            R.drawable.ping_pong,
            R.drawable.coffee,
            R.drawable.rice,
            R.drawable.pig,
            R.drawable.rose,
            R.drawable.wilt,
            R.drawable.lips,
            R.drawable.heart,
            R.drawable.broken_heart,
            R.drawable.cake,
            R.drawable.lightning,
            R.drawable.bomb,
            R.drawable.dagger,
            R.drawable.soccer,
            R.drawable.lady_bug,
            R.drawable.poop,
            R.drawable.moon,
            R.drawable.sun,
            R.drawable.gift,
            R.drawable.hug,
            R.drawable.thumbs_up,
            R.drawable.thumbs_down,
            R.drawable.shake,
            R.drawable.peace,
            R.drawable.fight,
            R.drawable.beckon,
            R.drawable.fist,
            R.drawable.pinky,
            R.drawable.rock_on,
            R.drawable.nuh_uh,
            R.drawable.ok,
            R.drawable.in_love,
            R.drawable.blowkiss,
            R.drawable.waddle,
            R.drawable.tremble,
            R.drawable.aaagh,
            R.drawable.twirl,
            R.drawable.kotow,
            R.drawable.dramatic,
            R.drawable.jump_rope,
            R.drawable.surrender,
            R.drawable.hooray,
            R.drawable.meditate,
            R.drawable.smooch,
            R.drawable.taichi_l,
            R.drawable.taichi_r,
    };

    public static final String[] EmojiTextArray = {
            "[smile]",
            "[grimance]",
            "[drool]",
            "[scowl]",
            "[cool_guy]",
            "[sob]",
            "[shy]",
            "[silent]",
            "[sleep]",
            "[cry]",
            "[akward]",
            "[angry]",
            "[tongue]",
            "[grin]",
            "[surprise]",
            "[frown]",
            "[ruthless]",
            "[blush]",
            "[scream]",
            "[puke]",
            "[chuckle]",
            "[joyful]",
            "[slight]",
            "[smug]",
            "[hungry]",
            "[drowsy]",
            "[panic]",
            "[sweat]",
            "[laugh]",
            "[commando]",
            "[determined]",
            "[scold]",
            "[shocked]",
            "[shhh]",
            "[dizzy]",
            "[tormented]",
            "[toasted]",
            "[skull]",
            "[hammer]",
            "[wave]",
            "[speechless]",
            "[nose_pick]",
            "[clap]",
            "[shame]",
            "[trick]",
            "[bah_l]",
            "[bah_r]",
            "[yawn]",
            "[pooh_pooh]",
            "[shrunken]",
            "[tearing_up]",
            "[sly]",
            "[kiss]",
            "[wrath]",
            "[whimper]",
            "[cleaver]",
            "[watermelon]",
            "[beer]",
            "[basketball]",
            "[ping_pong]",
            "[coffee]",
            "[rice]",
            "[pig]",
            "[rose]",
            "[wilt]",
            "[lips]",
            "[heart]",
            "[broken_heart]",
            "[cake]",
            "[lightning]",
            "[bomb]",
            "[dagger]",
            "[soccer]",
            "[lady_bug]",
            "[poop]",
            "[moon]",
            "[sun]",
            "[gift]",
            "[hug]",
            "[thumbs_up]",
            "[thumbs_down]",
            "[shake]",
            "[peace]",
            "[fight]",
            "[beckon]",
            "[fist]",
            "[pinky]",
            "[rock_on]",
            "[nuh_uh]",
            "[ok]",
            "[in_love]",
            "[blowkiss]",
            "[waddle]",
            "[tremble]",
            "[aaagh]",
            "[twirl]",
            "[kotow]",
            "[dramatic]",
            "[jump_rope]",
            "[surrender]",
            "[hooray]",
            "[meditate]",
            "[smooch]",
            "[taichi_l]",
            "[taichi_r]",
    };

    static {
        emojiList = generateEmojis();
    }

    public static int calculateInSampleSize(BitmapFactory.Options options,
                                            int reqWidth, int reqHeight) {
        // 源图片的高度和宽度
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            // 计算出实际宽高和目标宽高的比率
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            // 选择宽和高中最小的比率作为inSampleSize的值，这样可以保证最终图片的宽和高
            // 一定都会大于等于目标的宽和高。
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
                                                         int reqWidth, int reqHeight) {
        // 第一次解析将inJustDecodeBounds设置为true，来获取图片大小
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);
        // 调用上面定义的方法计算inSampleSize值
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        // 使用获取到的inSampleSize值再次解析图片
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }


    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale );
    }

    public static void handlerEmojiText(TextView comment, String content, Context context) throws IOException {
        SpannableStringBuilder sb = new SpannableStringBuilder(content);
        String regex = "\\[[a-zA-Z0-9_\\u4e00-\\u9fa5]+\\]"/*"\\[(\\S+?)\\]"*/;
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(content);
        Iterator<Emoji> iterator;
        Emoji emoji = null;
        while (m.find()) {
            iterator = emojiList.iterator();
            String tempText = m.group();
            while (iterator.hasNext()) {
                emoji = iterator.next();
                if (tempText.equals(emoji.getContent())) {
                    //转换为Span并设置Span的大小
                    sb.setSpan(new ImageSpan(context, decodeSampledBitmapFromResource(context.getResources(), emoji.getImageUri()
                                    , dip2px(context, 13.5f), dip2px(context, 13.5f))),
                            m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    break;
                }
            }
        }
        comment.setText(sb);
    }
}
